from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from django.conf import settings
import re, io, datetime, os, json
from .models import *
from user.models import *
from room.models import *
from contract.models import *

def create_pdf(user_name, uid_number, room_position, room_area, rent_period, money):
    buffer = io.BytesIO()
    column = 75
    row = 80
    diff = 25
    sub_diff = 15
    underline = '____________'
    now = datetime.datetime.now()
    ddl = now + datetime.timedelta(days=1)
    suffix = now.strftime("%Y-%m-%d")
    now = now.strftime("%Y年%m月%d日")
    ddl = ddl.strftime("%Y年%m月%d日")
    pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))  # 注册字体
    c = canvas.Canvas(buffer, bottomup=0)
    c.setFont("SimSun", 13)
    c.drawString(column, row, '甲方(出租方):青年租房管理系统')
    row += diff
    c.drawString(column, row, "乙方(承租方)：%s                身份证号码：%s" %(user_name, uid_number))
    row += diff
    c.drawString(column, row, '现经甲乙双方充分了解、协商，一致达成如下租房合同：')
    row += diff
    c.drawString(column, row, '一、房屋位于%s，建筑面积%.2f平方米。' % (room_position, room_area))
    row += diff
    c.drawString(column, row, '二、租赁期限：%d月，即%s至%s。' % (rent_period, now, ddl))
    row += diff
    c.drawString(column, row, '三、租金及交纳时间：每月%d元，乙方应每月付一次，于每月最后一星期内' % money)
    row += sub_diff
    c.drawString(column, row, '交付租金。')
    row += diff
    c.drawString(column, row, '四、租房押金：乙方应于签约同时付给甲方押金2000元，到期结算，多余归还。')
    row += diff
    c.drawString(column, row, '五、租赁期间的其他约定事项：')
    row += diff
    c.drawString(column, row, '1. 甲乙双方应提供真实有效的房产证、身份证等证件。')
    row += diff
    c.drawString(column, row, '2. 甲方提供完好的房屋、设施、设备，乙方应注意爱护，不得破坏房屋装修、')
    row += sub_diff
    c.drawString(column, row, '结构及设施、设备，否则应按价赔偿。')
    row += diff
    c.drawString(column, row, '3. 水、电、煤气、电话、网络、有线电视等的使用费及物业、电梯、卫生费等')
    row += sub_diff
    c.drawString(column, row, '所有费用都由乙方支付。')
    row += diff
    c.drawString(column, row, '4. 房屋只限乙方使用，乙方不得私自转租、改变使用性质或供非法用途。')
    row += diff
    c.drawString(column, row, '5. 合同一经签订，双方都不得提前解除。租赁期内，如遇不可抗力因素导致无')
    row += sub_diff
    c.drawString(column, row, '法继续履行本合同的，本合同自然终止，双方互不承担违约责任。')
    row += diff
    c.drawString(column, row, '6. 甲乙双方约定，乙方如需开具房租发票，因此产生的税费由乙方支付。')
    row += diff
    c.drawString(column, row, '7. 此合同未尽事宜，双方可协商解决，并作出补充条款，补充条款与本合同有')
    row += sub_diff
    c.drawString(column, row, '同等效力。双方如果出现纠纷，先友好协商，协商不成的，由人民法院裁定。')
    row += diff
    c.drawString(column, row, '8. 本合同经签字(盖章)生效。')
    row += diff
    c.drawString(column, row, '六、本合同一式两份，甲乙两方各执一份，具有同等法律效力。')
    row += diff
    c.drawString(column, row, '甲方(签章)：%-25s乙方(签章)：%-25s' % (underline, underline))
    row += diff
    c.drawString(column, row, '联系电话：%-27s联系电话：%-25s' % ('18949871109', underline))
    row += diff
    c.drawString(column, row, '签约日期：%-24s签约日期：______年___月___日' % now)
    row += diff
    c.showPage()
    c.save()
    file_path = '{}/{}_{}.pdf'.format(settings.PDF_URL, user_name, suffix)
    file = open(file_path, mode='wb+')
    file.write(buffer.getvalue())
    file.close()
    return file_path

def create_contract(username, oid):
    user = User.objects.get(username=username)
    order = Order.objects.get(id=oid)
    user_info = UserInfo.objects.get(id=user.id)
    room = Room.objects.get(id=order.rid)
    contract = Contract()
    contract.uid=order.uid
    contract.rid=order.rid
    contract.oid = order.id
    contract.period=order.period
    contract.pdf_path = create_pdf(user_info.name, user_info.id_number,
                room.address, room.size, order.period, room.price)
    contract.save()
    order.ctid = contract.id
    order.save()

@csrf_exempt
def create_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            order = Order()
            rid = data_json.get('rid', 0)
            if Room.objects.filter(id=rid).exists():
                room = Room.objects.get(id=rid)
                order.rid = rid
                room.uid = order.uid = User.objects.get(username=username).id
                rent = data_json.get('rent', 0)
                room.status = order.rent = rent
                order.period = data_json.get('period', 0)
                order.startTime = data_json.get('startTime', "")
                order.endTime = data_json.get('endTime', "")
                order.price = room.price
                order.address = room.address
                order.desc = data_json.get('desc', "")
                order.save()
                room.save()
                # if rent == 2:
                create_contract(username, order.id)
                return JsonResponse({'errno': 0, 'msg': "创建成功", 'oid': order.id})
            else:
                return JsonResponse({'errno': 1004, 'msg': "房间不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def check_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        oid = data_json.get('oid', 0)
        username = request.session.get('username', "")
        res = data_json.get('res', 0)
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        elif not User.objects.get(username=username).admin:
            return JsonResponse({'errno': 1003, 'msg': "非管理员用户"})
        elif not Order.objects.filter(id=oid).exists():
            return JsonResponse({'errno': 1004, 'msg': "订单不存在"})
        else:
            order = Order.objects.get(id=oid)
            if order.status != 1:
                return JsonResponse({'errno': 1005, 'msg': "订单状态错误"})
            elif res == 0:
                order.delete()
                return JsonResponse({'errno': 0, 'msg': "审核不通过"})
            else:
                order.status = 2
                order.save()
                return JsonResponse({'errno': 0, 'msg': "审核通过"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def ensure_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        oid = data_json.get('oid', 0)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        if Order.objects.filter(id=oid).exists():
            order = Order.objects.get(id=oid)
            if(order.uid == User.objects.get(username=username).id):
                order.status = 3
                order.save()
                return JsonResponse({'errno': 0, 'msg': "确认订单成功"})
            else:
                return JsonResponse({'errno': 1004, 'msg': "用户登录信息错误"})
        else:
            return JsonResponse({'errno': 1003, 'msg': "订单不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def search_orders(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        elif User.objects.get(username=username).admin:
            res = []
            for order in Order.objects.all():
                res.append(order.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
        else:
            res = []
            for order in Order.objects.filter(uid=User.objects.get(username=username).id):
                res.append(order.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def lookup_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username')
        if username == "":
                return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            oid = data_json.get('oid', 0)
            if Order.objects.filter(id=oid).exists():
                order = Order.objects.get(id=oid)
                user = User.objects.get(username=username)
                if(order.uid == user.id or user.admin):
                    return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': order.get_info()})
                else:
                    return JsonResponse({'errno': 1004, 'msg': "用户登录信息错误"})
            else:
                return JsonResponse({'errno': 1003, 'msg': "订单不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def delete_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        oid = data_json.get('oid', 0)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        uid = User.objects.get(username=username).id
        if Order.objects.filter(id=oid).exists():
            order = Order.objects.get(id=oid)
            if(order.uid == uid):
                order.delete()
                return JsonResponse({'errno': 0, 'msg': "删除订单成功"})
            else:
                return JsonResponse({'errno': 1004, 'msg': "用户登录信息错误"})
        else:
            return JsonResponse({'errno': 1003, 'msg': "订单不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def extend_order(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        user = User.objects.get(username=data_json['username'])
        order = Order.objects.get(oid=data_json.get('oid', 0))
        if user.id == order.uid and user.username == request.session.get('username'):
            if order.rent == 2 and order.status == 2:
                new_period = data_json.get('period', 0)
                order.period += new_period
                order.save()
                return JsonResponse({'errno': 0, 'msg': "续约成功"})
            elif order.rent == 1:
                return JsonResponse({'errno': 1003, 'msg': "短租订单不可以续约"})
            else:
                return JsonResponse({'errno': 1004, 'msg': "订单已过期"})
        else:
            return JsonResponse({'errno': 1002, 'msg': "用户登录信息错误"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})
